<template>
  <div class="posts-container">
    <el-card v-for="(post, index) in posts" :key="post.id" class="post-card" @click="RecordAndGoToPost(post.id)">
      <img :src="getCoverImage(index)" class="post-cover" alt="Post Cover" />
      <h3>{{ post.title }}</h3>
      <p>{{ post.content }}</p>
      <div class="post-meta">
        <span>作者: {{ post.authorUsername }}</span>
        <span>发布时间: {{ formatDate(post.createdAt) }}</span>
      </div>
      <el-link @click.prevent="fetchResource(post.resourceId, post.resourceFileName)">
        {{ post.resourceFileName }}
      </el-link>
      <p>{{ post.resourceDescription }}</p>
    </el-card>
  </div>
</template>

<script lang="ts" setup>
import { useRouter } from 'vue-router'
import { useStore } from 'vuex'
import { ElMessage } from 'element-plus'
import axios from '../plugins/axios'

// 定义 props 的类型
interface Post {
  id: number;
  title: string;
  content: string;
  authorUsername: string;
  resourceId: string;
  resourceFileName: string;
  resourceDescription: string;
  createdAt: string;
}

// 使用 defineProps 并指定类型
const props = defineProps<{ posts: Post[] }>()

const store = useStore()
const router = useRouter()

// 获取封面图片 URL 的方法
const getCoverImage = (index: number) => {
  const coverImageCount = 20; // 假设有20张封面图片
  const imageIndex = (index % coverImageCount) + 1;
  return `/covers/${imageIndex}.jpg`;
}

const formatDate = (dateString: string) => {
  const options: Intl.DateTimeFormatOptions = {
    year: 'numeric',
    month: 'long',
    day: 'numeric',
    hour: '2-digit',
    minute: '2-digit'
  }
  return new Date(dateString).toLocaleDateString('zh-CN', options)
}

const fetchResource = async (resourceId: string, resourceFileName: string) => {
  try {
    const response = await axios.get(`/resources/${resourceId}`, {
      responseType: 'blob' // 设置响应类型为 blob
    })
    if (response.status === 200) {
      const url = window.URL.createObjectURL(new Blob([response.data]))
      const link = document.createElement('a')
      link.href = url
      link.setAttribute('download', resourceFileName) // 设置下载文件的文件名
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
    } else {
      ElMessage.error('资源获取失败')
    }
  } catch (error) {
    ElMessage.error('资源获取失败')
    console.error('Error fetching resource:', error)
  }
}

const RecordAndGoToPost = async (postId: number) => {
  try {
    const user = store.getters.getUser
    const response = await axios.post(`/posts/record/${postId}?userId=${user.id}`)
    if (response.data.status === 200) {
      console.log(response.data.message)
    } else {
      ElMessage.error(response.data.message)
    }
  } catch (error) {
    console.error('Failed to record post view:', error)
  }
  router.push(`/post/${postId}`)
}
</script>

<style scoped>
.posts-container {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(600px, 1fr));
  gap: 20px;
  padding: 20px;
}

.post-card {
  margin: 0 auto;
  cursor: pointer;
}

.post-cover {
  width: 100%;
  height: auto; /* 保持图片的宽高比 */
  object-fit: cover; /* 确保图片覆盖整个容器 */
  margin-bottom: 10px; /* 图片与内容之间的间距 */
}

.post-meta {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
}
</style>